import { isLogin } from './login'
export function request(url, data, method = 'get') {
  const whiteUrl = ['/user/wxsigin']

  const config = {
    timeout: 10000,
    baseUrl: 'https://api.gnf2023.cn/api/app' + url,
    header: {}
  }
  if (!whiteUrl.includes(url)) {
    if (!uni.getStorageSync('tokens')) {
      // return
    }
    config.header.tokens = uni.getStorageSync('tokens')
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseUrl,
      data,
      method,
      timeout: config.timeout,
      header: config.header,
      success: async (res) => {
        // console.log(res.data.code == 401)
        if (Number(res.data.code) === 401) {
          if (await isLogin(true)) {
            console.log('重新请求')
            config.header.tokens = uni.getStorageSync('tokens')
            uni.request({
              url: config.baseUrl,
              data,
              method,
              timeout: config.timeout,
              header: config.header,
              success: (res) => {
                console.log('重新请求成功')
                resolve(res)
              },
              fail: (err) => {
                resolve(err)
              }
            })
          }
        } else {
          resolve(res)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
